<template>
  <div class="login_box">
    <a-form :model="loginForm" name="basic" autocomplete="off" @finish="onFinish" @finishFailed="onFinishFailed"
      layout="vertical">
      <a-form-item label="账号/邮箱/手机号" name="username" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input v-model:value="loginForm.username" placeholder="请输入账号" size="large" />
      </a-form-item>
      <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }]">
        <a-input-password v-model:value="loginForm.password" placeholder="请输入密码" size="large" />
      </a-form-item>
      <a-form-item label="验证码" name="imgcode" :rules="[{ required: true, message: '请输入验证码' }]">
        <a-input v-model:value="loginForm.imgcode" placeholder="请输入验证码" size="large">
          <template #suffix>
            <ImgCode ref="imgcode"></ImgCode>
          </template>
        </a-input>
      </a-form-item>
      <slot></slot>
      <a-form-item>
        <div class="submin_btn_box">
          <a-button type="primary" html-type="submit" size="large" :block="true">登录</a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { getEmail, userLogin } from "@/api/user";
import { message } from "ant-design-vue";
import ImgCode from "@/components/imgCode/index.vue";

const imgcode = ref<any>(null);
const router = useRouter();

interface loginForm {
  username: string;
  password: string;
  imgcode: number | string;
}

const loginForm = reactive<loginForm>({
  username: "",
  password: "",
  imgcode: "",
});

const key = "加载中…………";

const onFinish = async (values: any) => {
  message.loading({ content: "Loading...", key });

  const res = await userLogin({
    username: loginForm.username,
    password: loginForm.password,
    image_code: loginForm.imgcode,
  });

  if (res.data.code != 0) {
    message.error({
      content: res.data.msg,
      key,
    });
    console.log(imgcode.value);
    imgcode.value.getNewCodeImg();
    return;
  }

  window.localStorage.setItem("userInfo", JSON.stringify(res.data.data));
  router.push({ path: "/" });
  message.success({
    content: res.data.msg,
  });
};

const onFinishFailed = (errorInfo: any) => {
  message.loading({ content: "Loading...", key });
  setTimeout(() => {
    message.error({ content: "请填写完整", key, duration: 2 });
  });
};
</script>

<style lang="scss" scoped>
.submin_btn_box {
  text-align: center;
  margin: 0 auto;
  margin-top: 20px;
  width: 80%;
}
</style>
